package com.sc.ktapplication.module.activity

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import com.alibaba.fastjson.JSON
import com.sc.ktapplication.R
import com.sc.ktapplication.common.base.BaseActivity
import com.sc.ktapplication.common.constant.MMKVConstant
import com.sc.ktapplication.common.util.MMKVUtil
import com.sc.ktapplication.common.util.RsaUtils.MD5Utils
import com.sc.ktapplication.common.util.ToastUtil
import com.sc.ktapplication.module.entity.AppUser
import com.tbruyelle.rxpermissions3.RxPermissions
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : BaseActivity() {

    private val viewModel by viewModels<LoginViewModel>()

    override fun getLayoutId(): Int {
       return R.layout.activity_login
    }

    override fun showErrorMsg() {
        showErrorMsg(container,viewModel)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel.appUser.observe(this, Observer { appUser ->
            dismissLoadingDialog()
            saveUser(appUser)
            toMainPage()
        })
        requestPermissions()
    }



    private fun toMainPage(){
        intent = Intent(this,MainActivity::class.java)
        startActivity(intent)
    }

    private fun saveUser(appUser: AppUser){
        MMKVUtil.putString(MMKVConstant.APP_USER, JSON.toJSONString(appUser))
    }

    fun login(view : View){
        showLoadingDialog()
        val params = hashMapOf<String,Any>()
        params["etc"] = System.currentTimeMillis()
        params["loginName"] = etUserName.text.toString()
        params["password"] = MD5Utils.encode(etPassword.text.toString())
        viewModel.login(params)
    }


    private fun requestPermissions() {
        RxPermissions(this).request(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CALL_PHONE
        ).subscribe()
    }
}
